<?php

namespace Regard\InstituteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Regard\InstituteBundle\Entity\Category;
use Regard\InstituteBundle\Entity\Tariff;
use Regard\InstituteBundle\Form\CategoryType;
use Regard\InstituteBundle\Form\TariffType;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class InstituteController extends Controller
{
	public function listCategoriesAction()
	{
        $view = 'RegardInstituteBundle:Institute:listCategories.html.twig';
        
        $entityManager = $this->getDoctrine()
                            ->getManager();
        
        // get the categories list
        $categories = $entityManager->getRepository('RegardInstituteBundle:Category')->findBy(array(), array('superCategory' => 'asc', 'title' => 'asc'));
        
        $parameters = array(
            'categories' => $categories
        );
        
        return $this->render($view, $parameters);
	}
	
	public function listCaresAction($categoryId, $categoryName)
	{
        $view = 'RegardInstituteBundle:Institute:listCares.html.twig';
		$isTariffType = true;
		$superCategory = 'tarif';
        
        $entityManager = $this->getDoctrine()
                            ->getManager();
        
		$tariffList = $entityManager->getRepository('RegardInstituteBundle:Tariff')->findBy(array('category' => $categoryId));
        
		$category = $entityManager->getRepository('RegardInstituteBundle:Category')->findBy(array('id' => $categoryId));
            
		if ($category[0]->getSuperCategory() == 'tarif' || $category[0]->getSuperCategory() == 'soin') {
			$isTariffType = true;
		} elseif ($category[0]->getSuperCategory() == 'specs') {
			$isTariffType = false;
		}
		
        $parameters = array(
            'tariffList' => $tariffList,
			'categoryId' => $categoryId,
			'categoryName' => $categoryName,
			'isTariffType' => $isTariffType
        );
        
        return $this->render($view, $parameters);
	}
	
	/** /
    public function listCaresByCategoryAction()
    {
        $view = 'RegardInstituteBundle:Institute:listCares.html.twig';
        $tariffTable = array();
        
        $entityManager = $this->getDoctrine()
                            ->getManager();
        
        // get the categories list
        $categories = $entityManager->getRepository('RegardInstituteBundle:Category')->findAll();
        
        // foreach category get the tariff list
        foreach ($categories as $category) {
            $tariffList = $entityManager->getRepository('RegardInstituteBundle:Tariff')->findBy(array('category' => $category->getId()));
            $tariffTable[$category->getTitle()] = $tariffList;
        }
        
        $parameters = array(
            'tariffTable' => $tariffTable
        );
        
        return $this->render($view, $parameters);
    }
	/**/
	
	/**
     * @Secure(roles="ROLE_ADMIN")
     * @return render view
     */
    public function addCategoryAction() 
    {
        $view = 'RegardInstituteBundle:Institute:addEditCategory.html.twig';
		
		$request = $this->get('request');
		$category = new Category();
		
		$form = $this->createForm(new CategoryType, $category);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($category);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Catégorie ajoutée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_institute_list_categories'));
			} else {
				$this->get('session')->getFlashBag()->add('notice', 'Erreur : Formulaire invalide');
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'category' => $category));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $categoryId
     * @return render view
     */
    public function editCategoryAction($categoryId) 
    {
        $view = 'RegardInstituteBundle:Institute:addEditCategory.html.twig';
		
		$request = $this->get('request');
		
		if (!$category = $this->getDoctrine()->getManager()->getRepository('RegardInstituteBundle:Category')->find($categoryId)) {
			throw new NotFoundHttpException('Cette catégorie n\'existe pas');
		}
		
		$form = $this->createForm(new CategoryType, $category);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($category);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Catégorie modifiée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_institute_list_categories'));
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'category' => $category));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $categoryId
     * @return render view
     */
    public function removeCategoryAction($categoryId) 
    {
		if (!$brand = $this->getDoctrine()->getManager()->getRepository('RegardInstituteBundle:Category')->find($categoryId)) {
			throw new NotFoundHttpException('Cette catégorie n\'existe pas');
		}
		
		$em = $this->getDoctrine()->getManager();
		$em->remove($brand);
		$em->flush();
		
		$repoTariff = $this->getDoctrine()->getManager()->getRepository('RegardInstituteBundle:Tariff');
		
		$tariffs = $repoTariff->findBy(array('category' => $categoryId));
		
		foreach ($tariffs as $tariff) {
			$em->remove($tariff);
		}
		
		$em->flush();
		
		$this->get('session')->getFlashBag()->add('notice', 'Catégorie et soins associés supprimés');
				
		// redirect to avoid resubmission
		return new RedirectResponse($this->generateUrl('regard_institute_list_categories'));
    }
	
	/**
     * @Secure(roles="ROLE_ADMIN")
     * @return render view
     */
    public function addCaresAction($categoryId) 
    {
        $view = 'RegardInstituteBundle:Institute:addEditCares.html.twig';
		
		$request = $this->get('request');
		$tariff = new Tariff();
		
		$form = $this->createForm(new TariffType, $tariff);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($tariff);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Soin ajouté');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_institute_list_cares', array('categoryId' => $categoryId)));
			} else {
				$this->get('session')->getFlashBag()->add('notice', 'Erreur : Formulaire invalide');
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'tariff' => $tariff,
                                        'categoryId' => $categoryId));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $tariffId
     * @return render view
     */
    public function editCaresAction($tariffId) 
    {
        $view = 'RegardInstituteBundle:Institute:addEditCares.html.twig';
		
		$request = $this->get('request');
		
		if (!$tariff = $this->getDoctrine()->getManager()->getRepository('RegardInstituteBundle:Tariff')->find($tariffId)) {
			throw new NotFoundHttpException('Ce soin n\'existe pas');
		}
		
		$form = $this->createForm(new TariffType, $tariff);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($tariff);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Soin modifié');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_institute_list_cares', array('categoryId' => $tariff->getCategory())));
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'tariff' => $tariff,
                                        'categoryId' => $tariff->getCategory()));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $tariffId
     * @return render view
     */
    public function removeCaresAction($tariffId) 
    {
		if (!$tariff = $this->getDoctrine()->getManager()->getRepository('RegardInstituteBundle:Tariff')->find($tariffId)) {
			throw new NotFoundHttpException('Ce soin n\'existe pas');
		}
		
		$em = $this->getDoctrine()->getManager();
		$em->remove($tariff);
		$em->flush();
		
		$this->get('session')->getFlashBag()->add('notice', 'Soin supprimé');
				
		// redirect to avoid resubmission
		return new RedirectResponse($this->generateUrl('regard_institute_list_cares', array('categoryId' => $tariff->getCategory())));
    }
	
	public function __toString()
	{
		return strval($this->id);
	}

}
